package com.tuling.stu.service.tx;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.tuling.stu.dao.tx.TestDao;
import com.tuling.stu.entity.tx.Test2;

@Service
public class TestServiceImpl implements TestService {
	
	public static Logger logger = LoggerFactory.getLogger(TestServiceImpl.class);
	
	@Autowired
	private TestDao dao;
	
	@Transactional
	@Override
	public boolean addTest(Test2 test) throws IllegalArgumentException, IllegalAccessException {
		Test2 test1 = new Test2(-1L, "chenhs0058");
		Test2 test2 = new Test2(-2L, "qjr0057");
		try {
		//	addTest2(test2);	对象本身调用，此时不会开户事务
		/**  
		 * Spring中的日志或事务其实就是JDK或cglib动态代理, 也叫SpringAOP。
		 * 使用当前代理对象调用方法，开启一个新的事务；其实@Transational就是去连接池中取出一个连接资源	
		 */
			boolean serv = ((TestService)AopContext.currentProxy()).addTest2(test2);
		} catch (Exception e) {
			logger.info("addTest add defeat is not imporsaple.");
		}
		boolean flag = dao.addTest(test1);
		
		return flag;
	}

	@Transactional(propagation=Propagation.REQUIRES_NEW)
	@Override
	public boolean addTest2(Test2 test) throws IllegalArgumentException,  IllegalAccessException {
		boolean flag = dao.addTest(test);
		int r = 1/0;
		
		return flag;
	}

	
	@Autowired
	private TransactionTemplate transactionTemplate;
	
	@Override
	public boolean updateFlagById(final Integer id) throws Exception {
		
		boolean r = transactionTemplate.execute(new TransactionCallback<Boolean>() {

			@Override
			public Boolean doInTransaction(TransactionStatus status) {
				boolean rs = false;
				try {
					System.out.println("id: " + id);
					rs = dao.updateFlagById(id);
				//	int r = 1/0;
				} catch (Exception e) {
					status.setRollbackOnly();
					e.printStackTrace();
				}
				
				return rs;
			}
			
		});
		
		return r;
	}

	
	
}
